package cn.itsource.org.service.impl;

import cn.itsource.basic.PageList;
import cn.itsource.basic.basic.service.IBaseService;
import cn.itsource.basic.basic.service.impl.IBaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends IBaseServiceImpl<Department> implements IDepartmentService{
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional
    public void add(Department department){
        departmentMapper.insert(department);
        this.update(department);
    }


    @Override
    @Transactional
    public void update(Department department) {
        //拼接路径地址/../../..
        System.out.println(department.getParent().getId());
        if (department.getParent().getId() != null) {
            Department daddepartment = departmentMapper.selectById(department.getParent().getId());
            department.setPath(daddepartment.getPath() + "/" + department.getId());
        } else {
            department.setPath("/" + department.getId());
        }
        departmentMapper.update(department);
    }



    @Override
    public List<Department> queryTree() {
        //1.找到所有Department，坏处在于万一Department有很多，会非常占用内存，后期用redis解决

        //2.然后循环每个Department，看这个Department有没有父路径，如果有，就把这个Department放到他的
        //父Department下面的children里面

        //查询出所有数据
        List<Department> allDepts = departmentMapper.selectAll();
        // 把所有的数据转换成Map结构--后面查找自己的上级使用
        HashMap<Long, Department> deptMap = new HashMap<>();
        for (Department dept : allDepts) {
            deptMap.put(dept.getId(), dept);
        }
        //准备要返回的无限极树，把所有顶级部门返回到firstDepts中
        List<Department> firstDepts = new ArrayList<>();
        for (Department dept : allDepts) {
            //1.从所有数据中找出第一层级 firstDept   我们需要返回的数据
            if (dept.getParent_id() == null || dept.getParent_id().intValue() == 0) {
                firstDepts.add(dept);//最顶层的数据
            } else {
                // 第二\三\四。。。。\N 层
                //2.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Department parentDept = deptMap.get(dept.getParent_id());
                //判断上级部门是否存在
                if (parentDept != null) {
                    //如果存在，就把自己装进上级部门的children中
                    parentDept.getChildren().add(dept);
                }
            }

        }
        return firstDepts;
    }
}
